package com.heisen.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heisen.base.exception.RRException;
import com.heisen.base.utils.MyObjectUtils;
import com.heisen.database.service.impl.SuperServiceImpl;
import com.heisen.system.dto.DeptDto;
import com.heisen.system.entity.Dept;
import com.heisen.system.mapper.DeptMapper;
import com.heisen.system.query.DeptQuery;
import com.heisen.system.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heisen.system.vo.DeptVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author sen
 * @since 2023-12-24
 */
@Service
public class DeptServiceImpl extends SuperServiceImpl<DeptMapper,  Dept, DeptQuery> implements IDeptService {

    /**
     *  所有部门
     * @return
     */
    public List<Dept> deptList(){
        QueryWrapper<Dept> wq = new QueryWrapper<>();
        wq.orderByAsc(Dept.ORDER_NUM);
        return  this.baseMapper.selectList(wq);
    }


    @Override
    public List deptTree() {
        List<Dept> depts= deptList();
        return getDeptTree(depts , 0l);
    }


    /**
     * 树状 部门
     * @param depts
     * @param pId  父部门
     * @return
     */
    public  List getDeptTree( List<Dept> depts ,Long pId){
        if(pId == null) throw new RRException("父部门不能为空");
        List<DeptVo> deptVos = new ArrayList<>();
        for (Dept dept : depts) {
            DeptVo deptVo = new DeptVo();
            deptVo.setId(dept.getId());
            deptVo.setDeptName(dept.getDeptName());
            deptVo.setParentId(dept.getParentId());
            deptVos.add(deptVo);
        }

        /**
         * 树状 部门
         */
        List<DeptVo> treeDepts = new ArrayList<>();

        for (DeptVo deptVo : deptVos) {
            Long parentId = deptVo.getParentId();
            if(parentId!=null && parentId == pId){
                treeDepts.add(deptVo) ;
                continue;
            }
            for (DeptVo deptchildVo : deptVos) {
                Long deptId = deptchildVo.getId();
                if(deptId!=null && deptId == parentId ){
                    if (CollectionUtils.isEmpty(deptchildVo.getChildren()))
                        deptchildVo.initChildren();
                    deptchildVo.getChildren().add(deptVo);
                }
            }
        }
        return treeDepts;
    }


    /**
     * 查看当前本门有没有 下级部门
     */
    public Boolean useSubDept(Long id){
        if(MyObjectUtils.isEmpty(id)) throw new RRException("部门id 为空");
        QueryWrapper<Dept> wq = new QueryWrapper<>();
        wq.eq(Dept.PARENT_ID,id);
        List<Dept> depts = this.baseMapper.selectList(wq);
        if(MyObjectUtils.isEmpty(depts)) return false;
        return true;
    }
}
